<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部蓝色渐变背景，z-0 -->
    <view
      class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#2196F3] to-[#6ec6ff] rounded-b-[40rpx]"
    ></view>

    <!-- 吸顶搜索栏 z-30 -->
    <view class="sticky top-0 z-30 px-[32rpx] pt-[32rpx] pb-[0] bg-transparent">
      <SearchView />
      <view
        class="flex overflow-x-auto gap-x-[18rpx] py-[18rpx] scrollbar-hide"
      >
        <view
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="
            activeFilter === 0
              ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]'
              : 'bg-[#f5f7fa] text-[#2196F3]/80'
          "
          @click="activeFilterType(0,0)"
        >
          全部
        </view>
        <view
          v-for="(filter, index) in filters"
          :key="index"
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="
            activeFilter === index + 1
              ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]'
              : 'bg-[#f5f7fa] text-[#2196F3]/80'
          "
          @click="activeFilterType(index + 1,filter.id)"
        >
          {{ filter.name }}
        </view>
      </view>
    </view>

    <!-- 横向滚动筛选栏 z-20 -->
    <!-- <view class="sticky top-[112rpx] z-20 px-[32rpx] bg-transparent">
      <view class="flex overflow-x-auto gap-x-[18rpx] py-[18rpx] scrollbar-hide">
        <view 
          v-for="(filter, index) in filters" 
          :key="index"
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="activeFilter === index ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow border-[#2196F3]' : 'bg-[#f5f7fa] text-[#2196F3]/80'"
          @click="activeFilter = index"
        >
          {{ filter }}
        </view>
      </view>
    </view> -->

    <!-- 内容区整体下移 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[0]">
      <view class="p-[24rpx_32rpx] flex flex-col gap-y-[28rpx]">
        <view
          v-for="(bounty, index) in bounties"
          :key="index"
          @tap="handleBountyClick(bounty)"
          class="bg-white rounded-[28rpx] p-[32rpx] shadow-lg relative flex flex-col hover:shadow-xl transition-all duration-300"
        >
          <!-- 头部 -->
          <view class="flex justify-between items-center mb-[18rpx]">
            <view class="text-[32rpx] font-bold text-[#222] flex-1 truncate">{{
              bounty.title
            }}</view>
            <view
              class="text-[22rpx] px-[20rpx] py-[8rpx] rounded-[16rpx] font-medium bg-gradient-to-r from-[#e3f2fd] to-[#bbdefb] text-[#2196F3]"
              >{{ bounty.status }}</view
            >
          </view>
          <!-- 发布人 -->
          <view class="flex items-center mb-[10rpx]">
            <view
              class="w-[40rpx] h-[40rpx] rounded-full bg-gradient-to-br from-[#2196F3] to-[#6ec6ff] flex items-center justify-center mr-[12rpx] overflow-hidden"
            >
              <img
                :src="bounty.publisherAvatar"
                class="w-full h-full object-cover"
                alt="发布者头像"
              />
            </view>
            <view class="text-[24rpx] text-[#2196F3] font-medium">{{
              bounty.publisherName
            }}</view>
          </view>
          <!-- 描述 -->
          <view
            class="text-[26rpx] text-[#666] mb-[10rpx] leading-[1.7] line-clamp-2"
            >{{ bounty.desc }}</view
          >
          <!-- 分阶段任务 -->
          <view
            v-if="bounty.hasPhase"
            class="my-[10rpx] p-[18rpx] bg-gradient-to-r from-[#e3f2fd] to-[#bbdefb] rounded-[12rpx] border-l-[6rpx] border-l-[#2196F3]"
          >
            <view class="flex justify-between text-[24rpx] mb-[6rpx]">
              <view class="font-bold">第一阶段：风格提案</view>
              <view class="text-[#43a047] font-bold">已付款</view>
            </view>
            <view class="text-[22rpx]">金额：¥500 | 截止：明天 18:00</view>
          </view>
          <!-- 元信息 -->
          <view
            class="flex justify-between text-[22rpx] text-[#90caf9] mb-[10rpx]"
          >
            <view>
              <view>发布时间：{{ bounty.publishTime }}</view>
              <view>交付截止：{{ bounty.deadline }}</view>
            </view>
            <view
              class="text-[36rpx] font-bold text-[#FF4D4F] text-right my-[8rpx]"
              >{{ bounty.amount }}</view
            >
          </view>
          <!-- 标签 -->
          <view class="flex flex-wrap gap-x-[10rpx] gap-y-[10rpx] mb-[10rpx]">
            <view
              v-for="(tag, tIndex) in bounty.tags"
              :key="tIndex"
              class="text-[20rpx] px-[16rpx] py-[6rpx] bg-[#e3f2fd] rounded-[10rpx] text-[#2196F3] font-medium"
            >
              {{ tag }}
            </view>
          </view>
          <!-- 底部 -->
          <view class="flex justify-between items-center mt-[10rpx]">
            <view class="text-[22rpx] text-[#90caf9]"
              >已申请：{{ bounty.applyCount }}人</view
            >
            <nut-button
              size="small"
              type="primary"
              @click="handleApply(bounty.title)"
            >
              查看详情
            </nut-button>
          </view>
        </view>
      </view>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { ref } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import SearchView from "@/components/SearchView.vue";
import { post } from "@/utils/request";
import { title } from "process";
// import { Input as nutInput, Button as nutButton } from '@nutui/nutui-taro'

// 定义接口
interface CategoryColumn {
  update_time: null | number;
  create_time: number;
  name: string;
  id: number;
}

interface CategoryItem {
  columns: CategoryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface taskItem {
  // 任务标题
  title?: string;
  // 任务状态（如：新发布、进行中、已完成等）
  status?: string;
  // 任务状态样式类（用于前端渲染状态标签的样式）
  statusClass?: string;
  // 发布者头像（可为文字头像或图片URL）
  publisherAvatar?: string;
  // 发布者名称（含认证信息）
  publisherName?: string;
  // 任务描述（核心需求简述）
  desc?: string;
  // 发布时间（相对时间描述，如：2小时前）
  publishTime?: string;
  // 截止时间（相对时间描述，如：3天后）
  deadline?: string;
  // 任务金额（带货币符号）
  amount?: string;
  // 任务标签（用于分类和筛选）
  tags?: string[];
  // 任务类别
  type?: string;
  // 申请人数（任务热度指标）
  applyCount?: number;
  // 是否为阶段性任务（true：是；false：否）
  hasPhase?: boolean;
  // 任务是否禁用（true：不可操作；false：可操作）
  disabled?: boolean;
}

// export interface taskDataItem {
//   id?: number;
//   city?: string;
//   // 周期
//   cycle?: string;
//   // 截止日期
//   deadline?: string;
//   // 描述
//   describe?: string;
//   // 行业ID
//   industryId?: string;
//   // 是否上热门 0 不  1 上
//   recommend?: number;
//   // 主任务状态  0 发布中 1 进行中 2 待确认完成 3 确认没完成 4 确认已完成
//   status?: number;
//   taskStages?: TaskStageVo[];
//   // 类型
//   taskType?: number;
//   // 标题
//   title?: string;
// }

// export interface TaskStageVo {
//     // 任务周期(天)
//     cycle?: number;
//     // 描述 (注意：此字段类型可能有误，应为string?)
//     describe?: number;
//     id?: number;
//     price?: number;
//     // 任务状态  0所有  1 发布中  2 进行中 3 待确认完成 4 确认没完成 5 确认已完成(待评价) 6 已评价
//     status?: number;
//     // 任务ID
//     taskId?: number;
//     [property: string]: any;
// }

// 搜索文本
const searchText = ref<taskItem[]>([]);

// 筛选条件
// const filters = ['全部', '设计类', '开发类', '文案类', '运营类', '咨询类', '数据类', '本地服务']
const filters = ref<{ id: number; name: string }[]>([]);
const activeFilter = ref(0);

const activeFilterType = (index:number,typeid:number) => {
  activeFilter.value = index
  getTaskAll(typeid)
  typeid.value = typeid
} 

// 表单数据
// const formData = ref<taskDataItem[]>([]);
const TaskStageVo = ref<TaskStageVo[]>([]);

// 悬赏任务数据
const bounties = ref([
  {
    id: 7,
    title: "网站前端开发",
    status: "新发布",
    statusClass: "bg-[#e6f7ff] text-[#1890ff]",
    publisherAvatar: "天",
    publisherName: "天行科技 · 企业认证",
    desc: "需要开发公司官网前端页面，需熟悉React框架，响应式设计，要求7天内完成交付。有现成设计稿...",
    publishTime: "2小时前",
    deadline: "3天后",
    amount: "￥1200",
    tags: ["前端开发", "React", "响应式"],
    applyCount: 18,
    hasPhase: false,
    disabled: false,
  },
  {
    id: 2,
    title: "移动应用UI设计",
    status: "执行中",
    statusClass: "bg-[#f6ffed] text-[#52c41a]",
    publisherAvatar: "智",
    publisherName: "智能生活 · 平台认证",
    desc: "智能家居控制APP界面设计，需要提供风格稿、主界面设计和完整设计规范。分三个阶段付款...",
    publishTime: "1天前",
    deadline: "6天后",
    amount: "￥3500",
    tags: ["UI设计", "移动端", "交互设计"],
    applyCount: 37,
    hasPhase: true,
    disabled: false,
  },
  {
    id: 3,
    title: "产品文案撰写（中英双语）",
    status: "新发布",
    statusClass: "bg-[#e6f7ff] text-[#1890ff]",
    publisherAvatar: "海",
    publisherName: "海外优选 · 企业认证",
    desc: "为跨境电商产品撰写产品介绍文案（中英文各一版），需要突出产品特点和优势，吸引目标客户...",
    publishTime: "4小时前",
    deadline: "2天后",
    amount: "￥800",
    tags: ["文案撰写", "英文文案", "产品营销"],
    applyCount: 7,
    hasPhase: false,
    disabled: false,
  },
  {
    id: 4,
    title: "微信公众号运营（3个月）",
    status: "多人承接",
    statusClass: "bg-[#fff7e6] text-[#fa8c16]",
    publisherAvatar: "教",
    publisherName: "教育优选 · 平台认证",
    desc: "长期合作！需要专业的教育领域运营人才，负责公众号内容规划、撰写、排版和数据分析...",
    publishTime: "2天前",
    deadline: "每月考核",
    amount: "￥5000/月",
    tags: ["公众号运营", "内容创作", "教育行业"],
    applyCount: 46,
    hasPhase: false,
    disabled: false,
  },
]);
// 当前角色
const currentRole = ref("user"); // user, worker, merchant

// 处理搜索
const handleSearch = () => {
  Taro.showToast({
    title: `搜索: ${searchText.value}`,
    icon: "none",
    duration: 2000,
  });
};

// 处理申请执行
const handleApply = (taskTitle) => {
  Taro.showToast({
    title: `您已申请执行任务: ${taskTitle}\n等待发布者审核...`,
    icon: "none",
    duration: 2000,
  });
};

// 处理Tab点击
const handleTabClick = (label) => {
  Taro.showToast({
    title: `已切换到: ${label}`,
    icon: "none",
    duration: 2000,
  });
};

const handleBountyClick = (bounty) => {
  Taro.navigateTo({
    url: `/pages/webs/task-details-reward-task-platform?id=${bounty.id}`,
  });
};

// 任务类型
const getTaskType = async () => {
  const res = await post("/dictionary/taskType",{
    id:1
  });
  console.log('任务类型==>',res)
  if (res.code == 0) {
    filters.value = res.data.map((item: any) => ({
      id: item.columns.id,
      name: item.columns.name,
    }))
  }
};
getTaskType();

// 任务数据
const getTaskAll = async (type:number) => {
  const res = await post("/task/all", {
    pageNo: 1,
    pageSize: 72,
    taskType: type,
    recommend: 0,
  });
  if (res.code == 0) {
    console.log("==>", res);
    bounties.value = res.data.map((item: CategoryItem) => ({
      title: item.columns.title,
      id: item.columns.id,
      amount: item.columns.total_amount,
      desc: item.columns.describe_str,
      tags: item.columns.labels?.split(",") || [],
      publisherName: item.columns.memberName,
      publisherAvatar: item.columns.pic,
      type: item.columns.type
    }));
  }
};
getTaskAll(0);
</script>
